import { insertVote } from "@/server/business/vote.js";
import { formatDate, getDeviceInfo, getSource } from "@/utils/common.js";
import {getUrlQuery} from '@/utils/common.js'
import {
  closeToast,
  showConfirmDialog,
  showLoadingToast,
  showNotify
} from "vant";
import { store } from "./store.js";

const route = getUrlQuery(); // url获取数据
const sysData = {}; // c端设备数据

const getSysData = () => {
  getSource().then((type) => {
    sysData.source = type || "h5";
  });
  const mobileInfo = getDeviceInfo();
  sysData.browseType = mobileInfo.browseType;
  sysData.deviceType = mobileInfo.model;
  sysData.osVersion = mobileInfo.os;
  sysData.startTime = formatDate(new Date(), "yyyy-MM-dd hh:mm:ss");
  sysData.voteId = route.id;
};
// 投票提醒
const voteTip = () => {
  showConfirmDialog({
    title: "投票成功！",
    message: "您已完成今天的投票，明天可继续参加。",
    cancelButtonText: "确定",
    confirmButtonText: "明天提醒我"
  })
    .then(() => {
      // on confirm 调用提醒接口
    })
    .catch(() => {
      // on cancel
    });
};
export const handleSubmit = (fun) => {
  getSysData();
  if (route.pageType === "view") {
    return showNotify({ type: "success", message: "预览投票" }); // 预览不可以进行投票
  }
  if (JSON.stringify(store.userInfo) === "{}" && !route.staffUserId) {
    return showNotify({ type: "danger", message: "未登录不可投票" }); // 未登录且非站内信
  }
  let list = [...store.checkList, ...store.objectTo].map((item) => {
    let obj = {
      ballotType: store.voteInfo.appBizVoteSetting.voteType,
      candidateId: item,
      voteId: route.id
    };
    if (store.voteInfo.appBizVoteSetting.voteType === "normal") obj.voteNum = 1;
    else if (store.voteInfo.appBizVoteSetting.voteType === "decision")
      obj.result = store.checkList.includes(item) ? 1 : -1;
    return obj;
  });
  if (list.length === 0)
    return showNotify({
      type: "danger",
      message: `请先选择${
        store.voteInfo.appBizVoteLayout.candidateTitle || "作品"
      }，再投票`
    });
  showLoadingToast({ message: "提交中...", forbidClick: true, duration: 0 });
  let params = {
    answerReqList: list,
    ...sysData,
    endTime: formatDate(new Date(), "yyyy-MM-dd hh:mm:ss"),
    userInfo: store.userInfo
  };
  if (route.staffUserId) {
    params.staffUserId = route.staffUserId;
  }
  insertVote(params)
    .then(({ data }) => {
      showNotify({ type: "success", message: "投票成功" });
      store.checkList = [];
      store.objectTo = [];
      closeToast();
      fun && fun();
      if (
        data.isTomorrowTip &&
        store.voteInfo.appBizVoteSetting.voteCycle === "perweek"
      ) {
        voteTip();
      }
    })
    .catch(() => {
      closeToast();
      store.checkList = [];
      store.objectTo = [];
    });
};
